﻿using CompanyManageSystem.Model;
using CompanyManageSystem.Service;
using DevExpress.XtraPrinting.HtmlExport.Native;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace CompanyManageSystem.UI.WeiXin
{
    public partial class Frm_WeiXin : Form
    {
        #region 属性
        //微信服务器返回信息
        public string rString = null;
        //全局唯一接口调用凭据
        public string Access_Token = null;
        //管理员
        public string Manager = null;
        //管理员ID
        public Guid ManagerID;
        #endregion

        #region 构造方法
        public Frm_WeiXin()
        {
            InitializeComponent();
        }
        public Frm_WeiXin(string manager, Guid managerID)
        {
            InitializeComponent();
            this.Manager = manager;
            this.ManagerID = managerID;
        }
        #endregion

        #region 界面加载完成
        private void WeiXin_Load(object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            InfoGrid.DataSource = aservice.GetWeiXinInfoByManagerID(this.ManagerID);
            //InfoGrid.DataSource = aservice.GetAllWeiXinInfo();

            this.Text = "管理员:" + this.Manager;
        }
        #endregion

        #region 点击按钮(未使用)
        private void simpleButton1_Click222(object sender, EventArgs e)
        {
            #region 读取目录文件内容
            //FileStream fs = new FileStream("E:\\Microsoft Visual Studio 2015 Projects\\CompanyManageSystem\\CompanyManageSystem\\menu2.txt", FileMode.Open);
            //StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
            //string postData = sr.ReadToEnd();
            //fs.Close();
            #endregion

            //菜单创建
            //string postData = "{\"button\":[{\"type\":\"click\",\"name\":\"饭堂专区\",\"key\":\"v1\"},{\"type\":\"click\",\"name\":\"客服专区\",\"key\":\"v2\"},{\"type\":\"click\",\"name\":\"菜单专区\",\"key\":\"vc\"}]}";

            string postData = "{\"button\":[{\"type\":\"click\",\"name\":\"邑大校区\",\"key\":\"v1\"},{\"type\":\"click\",\"name\":\"新生专区\",\"key\":\"v2\"},{\"type\":\"click\",\"name\":\"关于我们\",\"key\":\"vc\",\"sub_button\": [{\"type\":\"view\",\"name\":\"百度搜索\",\"url\":\"http://www.baidu.com\"},{\"type\":\"click\",\"name\":\"账号管理\",\"key\":\"v20\"},{\"type\":\"click\",\"name\":\"联系客服\",\"key\":\"v30\"}]  }]}";

            //群发信息
            //string data = "你这个麻瓜".Trim();
            //string postData = "{\"touser\":[\"oxcKRwa7ShX4LQJZ63DtZPVwlEQo\",\"oxcKRwZ8JV9UajsdNKFxdM54YSV0\"],\"msgtype\": \"text\",\"text\": { \"content\": \"" + data + "\"}}";

            //string url = "http://api.tianapi.com/weixin/?key=c60b442a8e551009d8dd05a251296a7b";

            //string url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=GY4DizbyuaHGtCS3hUrSQFr0dcnn8Th0NHPUYYLz0LAl2xkkxV5rQHRSCtKths8VEhIXT_34V-bCna6Zcy7e1wIuo_UhTCdPNSk18S_kuQzzHjFfMx0VPe8k5a0b4_7LCADbADAJHK";

            //string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=GY4DizbyuaHGtCS3hUrSQFr0dcnn8Th0NHPUYYLz0LAl2xkkxV5rQHRSCtKths8VEhIXT_34V-bCna6Zcy7e1wIuo_UhTCdPNSk18S_kuQzzHjFfMx0VPe8k5a0b4_7LCADbADAJHK";

            //从数据库获取Token
            AppService aservice = new AppService();
            var list = aservice.GetTokenInAToken();
            Access_Token = list[0];

            //微信服务器请求URL
            string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + Access_Token;
            //string url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + Access_Token;
            //string url = "https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token=" + Access_Token;

            RequestUrl(url, postData);
            //检测Access_Token是否过期或者是否拥有Access_Token
            if (rString.Contains("access_token expired") || rString.Contains("miss"))
            {
                string sUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
                //string sUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=";
                url = sUrl + GetToken("wxaf6c26b7b44a82be", "f9ee699f69184cd9ad17e93dd321e1b6");
                RequestUrl(url, postData);
            }

        }
        #endregion

        #region GridControl右键事件
        private void gridControl1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                popupMenu1.ShowPopup(Control.MousePosition);
            }
        }
        #endregion

        #region 发送信息按钮
        /// <summary>
        /// 发送信息按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //获取GridControl焦点行
            WeiXinInfo info = InfoView.GetFocusedRow() as WeiXinInfo;

            #region 切割OpenID
            //正则表达式要求,至少匹配1次，至多匹配次数没有限制
            string pattern = "[^\"]{1,}";     
            Regex regex = new Regex(pattern);
            MatchCollection mc = regex.Matches(GetAllOpenID());
            #endregion

            #region 微信操作
            //群发消息
            string postData = "{\"touser\":[\"";
            for (int i = 0; i < mc.Count; i++)
            {
                postData = postData + mc[i].Value.Replace(",", "\",\"");
            }
            postData = postData + "\"],\"msgtype\": \"text\",\"text\": { \"content\": \"" + info.Info + "\"}}";

            //服务号发送模板信息
            List<string> openID = new List<string>();
            openID.Add("oxcKRwa7ShX4LQJZ63DtZPVwlEQo");
            //openID.Add("oxcKRwZ8JV9UajsdNKFxdM54YSV0");
            //openID.Add("oKA2kxECey17MmFxdmYiuxGxEs5w"); //公司

            //发送模板消息的时候才用到循环
            for (int i = 0; i < openID.Count; i++)
            {
                //模板信息
                //string postData = "{\"touser\":\"" + openID[i] + "\",\"template_id\":\"KyA0IbjTVGqh4FKpfPJoD_LlyZwch2S6mmaQt6ZIUlo\",\"url\":\"http://www.baidu.com\", \"data\":{\"first\": {\"value\":\"您有一份新消息！\\n\",\"color\":\"#173177\"},\"keynote1\":{\"value\":\"巧克力\\n\",\"color\":\"#173177\"},\"keynote2\": {\"value\":\"39.8元\\n\",\"color\":\"#173177\"},\"keynote3\": {\"value\":\"2014年9月22日\\n\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎再次购买！\",\"color\":\"#173177\"}}}";
                //string postData = "{\"touser\":\"" + openID[i] + "\",\"template_id\":\"HJazf8gqrOEU35nB6bnI4uI5jHSUqLsMncUP40Qchww\",\"url\":\"http://www.baidu.com\" ,\"data\":{\"first\": {\"value\":\"您有一份新消息！\\n\",\"color\":\"#173177\"},\"keynote1\":{\"value\":\"五邑大学开学联欢晚会\\n\",\"color\":\"#173177\"},\"keynote2\": {\"value\":\"2016年9月6日\\n\",\"color\":\"#173177\"},\"keynote3\": {\"value\":\"五邑大学南区吕志和礼堂\\n\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎您的到来!\",\"color\":\"#173177\"}}}";
                //postData = "{\"touser\":\"oxcKRwa7ShX4LQJZ63DtZPVwlEQo\",\"template_id\":\"	8XYfrTIy7W-sAmXuo0Lv5c0LIApXhhWzbYw8eJ296Zc\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\": {\"value\":\"恭喜你购买成功！\",\"color\":\"#173177\"},\"goods_name\":{\"value\":\"巧克力\",\"color\":\"#173177\"},\"service_content\": {\"value\":\"39.8元\",\"color\":\"#173177\"},\"fee_money\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"cost_standard\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎再次购买！\",\"color\":\"#173177\"}}}";
                //postData = "{\"touser\":\"oxcKRwa7ShX4LQJZ63DtZPVwlEQo\",\"template_id\":\"AQgR0kfVH9Y5hseQfb4WnWmNSbDdrQM-remUya5BNyI\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\": {\"value\":\"恭喜你购买成功！\",\"color\":\"#173177\"},\"ecoupon\":{\"value\":\"巧克力\",\"color\":\"#173177\"},\"product\": {\"value\":\"39.8元\",\"color\":\"#173177\"},\"number\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"valid\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"location\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎再次购买！\",\"color\":\"#173177\"}}}";
                //postData = "{\"touser\":\"oxcKRwa7ShX4LQJZ63DtZPVwlEQo\",\"template_id\":\"gTq837G8XNQXyX-Rxyjd9SomPWxApj5A4bhWKotVwuI\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\": {\"value\":\"恭喜你购买成功！\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"巧克力\",\"color\":\"#173177\"},\"keyword2\": {\"value\":\"39.8元\",\"color\":\"#173177\"},\"keyword3\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"keyword4\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"keyword5\": {\"value\":\"2014年9月22日\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎再次购买！\",\"color\":\"#173177\"}}}";
                postData = "{\"touser\":\"oxcKRwa7ShX4LQJZ63DtZPVwlEQo\",\"template_id\":\"gyjeXdflK9dEhUqIU4kQWY1QAZM4t15glPhlKcXnjQs\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\": {\"value\":\"恭喜你购买成功！\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"巧克力\\n\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"巧克力\\n\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎再次购买！\",\"color\":\"#173177\"}}}";

                //从数据库获取Token
                AppService aservice = new AppService();
                var list = aservice.GetTokenInAToken();
                Access_Token = list[0];

                //微信服务器请求的URL
                //string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + Access_Token;
                //string url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + Access_Token;
                string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + Access_Token;

                //访问微信服务器
                RequestUrl(url, postData);

                //检测Access_Token是否过期或者是否拥有Access_Token
                if (rString.Contains("access_token expired"))
                {
                    string sUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=";
                    //string sUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

                    List<string> listID = aservice.GetAppIDInAToken();
                    List<string> listSecret = aservice.GetAppSecretInAToken();

                    url = sUrl + GetToken(listID[0], listSecret[0]);

                    #region 重复获取发送数据
                    mc = regex.Matches(GetAllOpenID());

                    //发送文字消息
                    postData = "{\"touser\":[\"";
                    for (int j = 0; j < mc.Count; j++)
                    {
                        postData = postData + mc[j].Value.Replace(",", "\",\"");
                    }
                    postData = postData + "\"],\"msgtype\": \"text\",\"text\": { \"content\": \"" + info.Info + "\"}}";

                    //发送模板信息
                    //postData = "{\"touser\":\"" + openID[i] + "\",\"template_id\":\"HJazf8gqrOEU35nB6bnI4uI5jHSUqLsMncUP40Qchww\", \"data\":{\"first\": {\"value\":\"您有一份新消息！\\n\",\"color\":\"#173177\"},\"keynote1\":{\"value\":\"五邑大学开学联欢晚会\\n\",\"color\":\"#173177\"},\"keynote2\": {\"value\":\"2016年9月6日\\n\",\"color\":\"#173177\"},\"keynote3\": {\"value\":\"五邑大学南区吕志和礼堂\\n\",\"color\":\"#173177\"},\"remark\":{\"value\":\"欢迎您的到来!\",\"color\":\"#173177\"}}}";
                    #endregion

                    RequestUrl(url, postData);
                }
            }
            #endregion
        }
        #endregion

        #region 微信方法

        #region 微信服务器请求
        /// <summary>
        /// 微信服务器请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        private void RequestUrl(string url, string postDataStr)
        {
            //直接访问http,获取Access_Token
            //System.Diagnostics.Process.Start(@'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxaf6c26b7b44a82be&secret=f9ee699f69184cd9ad17e93dd321e1b6');

            //访问微信服务器接口
            //string url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=3znVmfIk0KaV0LbLvHOGKRGwWZNzIphrhGCFRDQeQBqGibwrMXzt842kyePctKBzmmCLz-V6iV_PZ6PSpIw1-jJfkTav1jKi5P25-xryO5KrsYCVyYUMOvF9a1WQPyMbPMPaADAJGJ';

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  //访问URL
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            //Stream myRequestStream = request.GetRequestStream();
            //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
            //myStreamWriter.Write(postDataStr); 
            //myStreamWriter.Close();

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postDataStr);
            Stream stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);  //提交信息到微信服务器
            stream.Close();   //以上是POST数据的写入


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();

            rString = retString;

            if (retString.Contains("access_token expired"))
            {
                MessageBox.Show("Access_Token过期");
            }

            Console.WriteLine(retString);   //返回界面信息
            myStreamReader.Close();
            myResponseStream.Close();
        }
        #endregion

        #region 获取Access_Token
        /// <summary>
        /// 获取Access_Token
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="appSerect"></param>
        /// <returns></returns>
        private string GetToken(string appID, string appSerect)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSerect;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd(); //获取服务器返回的Json数据段

            //去掉Access_Token后面的字符串
            int index = 0;
            index = retString.LastIndexOf("\",");
            retString = retString.Substring(0, index);

            //去掉Access_Token前面的字符串
            retString = retString.Substring(17, retString.Length - 17);

            Access_Token = retString;

            AppService aservice = new AppService();
            List<Guid> listID = aservice.GetIDInAToken();
            //aservice.UpdateTokenByID("909eea04-ef8f-4cc6-9643-05ebceea0bb8", Access_Token);
            aservice.UpdateTokenByID(Convert.ToString(listID[0]), Access_Token);

            myStreamReader.Close();
            myResponseStream.Close();

            return Access_Token;
        }
        #endregion

        #region 获取所有OpenID
        /// <summary>
        /// 获取所有OpenID
        /// </summary>
        /// <returns></returns>
        private string GetAllOpenID()
        {
            AppService aservice = new AppService();
            List<string> list = new List<string>();
            list = aservice.GetTokenInAToken();

            string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + list[0];

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  //访问URL
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();

            //处理OpenID
            //去掉前面的字符串
            int bindex = 0;
            bindex = retString.IndexOf("[");
            retString = retString.Substring(bindex + 1, retString.Length - bindex - 1);

            //去掉后面的字符串
            int aindex = 0;
            aindex = retString.LastIndexOf("]");
            retString = retString.Substring(0, aindex);

            return retString;
        }
        #endregion

        #endregion

        #region 工具栏
        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Frm_AddWeiXin frm = new Frm_AddWeiXin(ManagerID, this.Manager);
            frm.SaveEvent += WeiXinInfo_AddSaveEvent;
            frm.ShowDialog();
        }
        private void WeiXinInfo_AddSaveEvent(Object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            InfoGrid.DataSource = aservice.GetWeiXinInfoByManagerID(this.ManagerID);
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("是否清除所有信息?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                //确定
                AppService aservice = new AppService();
                aservice.DelWeiXin(ManagerID);
                InfoGrid.DataSource = aservice.GetWeiXinInfoByManagerID(ManagerID);
            }
            else
            {
                //取消
            }
        }
        #endregion

        #region 指示器
        /// <summary>
        /// 指示器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InfoView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        #endregion



    }
}
